#include "keyvalue.h"

KeyValue::KeyValue(const char *fileName)
{
    file = fopen(fileName, "a+");
    if(file == NULL){
        perror("open init.cfg err:");
    }
}

KeyValue::~KeyValue()
{
    fclose(file);
}

void KeyValue::setValue(const char *key, const char *val)
{
    char record[128];
    sprintf(record, "%s=%s\n", key, val);

    if(fwrite(record, strlen(record), sizeof(char), file) <= 0){
        cout << "write err" <<endl;
    }else{
        cout << "write ok" <<endl;
    }
}

char *KeyValue::value(const char *key)
{
    static char record[128];
    bzero(record, 128);
    int ret;
    char *p = NULL;

    fseek(file, 0, SEEK_SET);  //先把文件指针定位到头部

    while(fgets(record, sizeof(record), file) != NULL)
    {
        record[strlen(record)-1] = '\0'; //去掉换行符
        ret=strncmp(record, key, strlen(key));
        if(ret==0 && record[strlen(key)]=='=')
        {
            p = record+strlen(key);
            p++;
            return p;
        }
    }
    cout << "not found key = " << key << endl;
    return NULL;
}
